// pages/login/login.js
//获取应用实例
const app = getApp()
const util = require('../../../utils/util.js')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    loading : 1, 
    itemIndex:0,
    detailIndex:0,
    checkItemList:[],
    filesData:[],
    imgUrlData:[] ,
    unbingError:0
  },
  onLoad: function(options) {
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      altitude: true,
      fail: (res) => {
        //不允许打开定位
        wx.hideLoading()
        wx.getSetting({
          success(res) {
            //开启小程序内定位
            if (res.authSetting["scope.userLocation"] == false) {
              wx.showModal({
                content: '请允许小程序使用地理位置功能！您可以在【我的】页面点击【设置】按钮快捷设置。',
                confirmText: "去设置",
                success: res => {
                  if (res.confirm) {
                    wx.switchTab({
                      url: '/pages/mine/mine'
                    })
                  }
                }
              })
            } else {
              //开启系统设置定位
              wx.getSystemInfo({
                success: res => {
                  console.log(res)
                  if (res.platform == "ios") {
                    that.setData({
                      locationContent: "请在系统设置-微信里开启允许微信使用地理位置的开关"
                    })
                  }
                  wx.showModal({
                    title: '未允许使用地理位置',
                    content: that.data.locationContent,
                    showCancel: false
                  })
                },
                fail: res => {
                  wx.showModal({
                    title: '未允许使用地理位置',
                    content: that.data.locationContent,
                    showCancel: false
                  })
                }
              })
            }

          }
        })
      },
      success: res => {
        console.log(res)
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          altitude: res.altitude
        })
      }
    })
    console.log("nfc巡检")
    let aid = options.aid
    this.setData({
      aid : aid
    })
    wx.request({
      url: app.inspectUrl + '/WeChat/weChatSystem/getNFCDeviceById',
      method: 'POST',
      dataType: 'json',
      data: {
        schoolId : parseInt(app.globalData.departmentId) ,
        macAddress : aid
      },
      success: res => {
        console.log(res)
        this.setData({
          deviceId : aid ,
          category: res.data.category,
          deviceName:res.data.deviceName
        })
        wx.request({
          url: app.inspectUrl + '/WeChat/weChatSystem/getNFCInspectItem',
          method: 'POST',
          dataType: 'json',
          data: {
            schoolId : parseInt(app.globalData.departmentId) ,
            macAddress : aid,
            deviceName: res.data.deviceName,
            category: res.data.category 
          },
          success: res2 => {
            console.log("item",res2.data)
            if(res2.data.length != 0){
              for (let i = 0; i < res2.data[0].contentList.length; i++) {
                res2.data[0].contentList[i].video = ""
                res2.data[0].contentList[i].videoSrc = ""
              }
              this.setData({
                checkItemList: res2.data
              })
            }else{
              this.setData({
                unbingError: 1
              })
            }
          },fail: res => {
            wx.showToast({
              title: '网络异常！',
              image: '/images/warning.png'
            })
          },complete: () => {
            this.setData({
              loading: 0
            })
          }
        })
      }
    })
    wx.removeStorage({
      key: 'fileAndImg'
    })
  },
  switchChange: function(e) {
    console.log(e.currentTarget.id)
    let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
    let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
    let checkItemList = this.data.checkItemList
    if (e.detail.value == false) {
      checkItemList[itemIndex].contentList[detailIndex].status = 0
      checkItemList[itemIndex].contentList[detailIndex].contentLength = 0
      checkItemList[itemIndex].contentList[detailIndex].dealFiles = []
      checkItemList[itemIndex].contentList[detailIndex].imageUrl = []
      checkItemList[itemIndex].contentList[detailIndex].hide = false
      checkItemList[itemIndex].contentList[detailIndex].imageNum = 0
      checkItemList[itemIndex].contentList[detailIndex].video = ""
      checkItemList[itemIndex].contentList[detailIndex].videoSrc = ""
      checkItemList[itemIndex].contentList[detailIndex].recordContent = ""
    } else {
      checkItemList[itemIndex].contentList[detailIndex].status = 1
      checkItemList[itemIndex].contentList[detailIndex].recordContent = ""
      checkItemList[itemIndex].contentList[detailIndex].video = ""
      checkItemList[itemIndex].contentList[detailIndex].videoSrc = ""
    }
    this.setData({
      checkItemList: checkItemList,
    })
  },
  onShow:function(e){
    var that = this;
    let checkItemList = that.data.checkItemList
    if(checkItemList.length != 0){
      that.setData({
        checkItemList: checkItemList
      })
    }
  },
  //自定义相机组件
  toCamera:function(e){
    let commit
    let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
    let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
    if (this.data.checkItemList[itemIndex].contentList[detailIndex].recordContent == null ||
        this.data.checkItemList[itemIndex].contentList[detailIndex].recordContent == undefined || this.data.checkItemList[itemIndex].contentList[detailIndex].recordContent == "") {
        commit = 0
    }
    if(commit == 0){
      wx.showToast({
        title: '请输入现场问题描述',
        image: "/images/warning.png"
      })
    }else{
      wx.navigateTo({
        url: '../cameraIdentified/cameraIdentified?recordContent='+
        this.data.checkItemList[itemIndex].contentList[detailIndex].recordContent+'&checkItemList='+JSON.stringify(this.data.checkItemList)+
        '&itemIndex='+itemIndex+'&detailIndex='+detailIndex+'&type=2'+'&address='+this.data.checkItemList[itemIndex].address
      })
    }
  },
  chooseImage: function(e) {
    var that = this;
    wx.chooseImage({
      count: 3,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        wx.showLoading({
          title: "图片上传中",
          mask: true
        })

        let tempImg = res.tempFilePaths
        for (let i = 0; i < tempImg.length; i++) {
          wx.uploadFile({
            url: app.inspectUrl + '/WeChat/weChatSystem/fileUpload',
            filePath: res.tempFilePaths[i],
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {
              if (res.data == "fail") {
                wx.showToast({
                  title: "图片上传失败",
                  image: "/images/error.png"
                })
              } else {
                wx.showToast({
                  title: "上传成功"
                })
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
                let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
                let checkItemList = that.data.checkItemList
                checkItemList[itemIndex].contentList[detailIndex].dealFiles.push(tempImg[i])
                checkItemList[itemIndex].contentList[detailIndex].imageUrl.push(res.data)
                checkItemList[itemIndex].contentList[detailIndex].imageNum++
                  that.setData({
                    checkItemList: checkItemList
                  })
                if (that.data.checkItemList[itemIndex].contentList[detailIndex].dealFiles.length == 3) {
                  checkItemList[itemIndex].contentList[detailIndex].hide = true
                  that.setData({
                    checkItemList: checkItemList
                  })
                }
              }
            },
            fail: res => {
              wx.showToast({
                title: "图片上传失败",
                image: "/images/error.png"
              })
            }
          })
        }

      }
    })
  },
  previewImageDeal: function(e) {
    let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
    let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
    let current = e.currentTarget.id.split('-')[2]
    let contentList = this.data.checkItemList[itemIndex].contentList[detailIndex]
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: contentList.dealFiles // 需要预览的图片http链接列表
    })
  },
  deleteImage: function(e) {
    let that = this
    let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
    let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
    let imgIndex = parseInt(e.currentTarget.id.split('-')[2])
    let contentList = this.data.checkItemList[itemIndex].contentList[detailIndex]
    let target = contentList.imageUrl[imgIndex]
    let dealFiles = contentList.dealFiles[imgIndex]
    let dealFilesStr = "checkItemList[" + itemIndex + "].contentList[" + detailIndex + "].dealFiles"
    let imageUrlStr = "checkItemList[" + itemIndex + "].contentList[" + detailIndex + "].imageUrl"
    let imageNumStr = "checkItemList[" + itemIndex + "].contentList[" + detailIndex + "].imageNum"
    let hideStr = "checkItemList[" + itemIndex + "].contentList[" + detailIndex + "].hide"
    let temp = []
    let tempUrl = []
    let dealFilesLength = contentList.dealFiles.length
    for (let i = 0; i < dealFilesLength; i++) {
      if (i != imgIndex) {
        temp.push(contentList.dealFiles[i])
        tempUrl.push(contentList.imageUrl[i])
      }
    }

    wx.showActionSheet({
      itemList: ['删除这张照片'],
      success: res => {
        if (!res.cancel) {
          that.setData({
            [dealFilesStr]: temp,
            [imageUrlStr]: tempUrl
          })
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/deleteFile',
            method: 'POST',
            data: {
              filename: target.split("image/")[1]
            },
            dataType: 'json',
            success: res => {
              let imageNum = contentList.imageNum - 1
              that.setData({
                [imageNumStr]: imageNum,
              })
              if (dealFilesLength == 3) {
                that.setData({
                  [hideStr]: false
                })
              }
            }
          })
        }
      }
    })
  },
  inputContent: function(e) {
    e.detail.value = app.trim(e.detail.value)
    let itemIndex = parseInt(e.target.id.split('-')[0]),
      detailIndex = parseInt(e.target.id.split('-')[1]),
      checkItemList = this.data.checkItemList
    checkItemList[itemIndex].contentList[detailIndex].contentLength = parseInt(e.detail.value.length)
    checkItemList[itemIndex].contentList[detailIndex].recordContent = e.detail.value
    this.setData({
      checkItemList: checkItemList
    })
  },
   //新增视频录制功能
   press:function (e) {
    let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
    let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
    let checkItemList = this.data.checkItemList
    wx.chooseVideo({
      sourceType: ['camera'],
      maxDuration: 10,
      camera: 'back',
      success: res => {
        if(res.size > 2097152){
          wx.showToast({
            title: '文件大于2M！',
            mask: true,
            image: "/images/error.png"
          })
        }else{
          wx.uploadFile({
            url: app.inspectUrl + '/WeChat/weChatSystem/fileUpload2',
            filePath: res.tempFilePath,
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success:res=>{
              console.log(res.data)
              checkItemList[itemIndex].contentList[detailIndex].video = res.data
              checkItemList[itemIndex].contentList[detailIndex].videoSrc = app.imageUrl + res.data
              this.setData({
                checkItemList: checkItemList
              })
            }
          })
        }
      },
      fail(res){
        console.log("-------调用失败")
      }
    })
  },
  delelteVideo:function(e) {
    let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
    let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
    let checkItemList = this.data.checkItemList
    let target = checkItemList[itemIndex].contentList[detailIndex].video
    wx.showActionSheet({
      itemList: ['删除视频'],
      success: res => {
        if (!res.cancel) {
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/deleteVideo',
            method: 'POST',
            data: {
              filename: target.split("video/")[1]
            },
            dataType: 'json',
            success: res => {
              if(res.data == "success"){
                checkItemList[itemIndex].contentList[detailIndex].video = ""
                this.setData({
                  checkItemList : checkItemList
                })
              }
            }
          })
        }
      }
    })
  },
  // 提交
  submit: util.throttle(function(e) {
    let list = this.data.checkItemList[0].contentList
    let that = this
    let commit
    let count = 0
    let unusualList = []
    for (let i = 0; i < list.length; i++) {
      if (list[i].status == 0) {
        if (list[i].recordContent == null || list[i].recordContent == undefined || list[i].recordContent == "") {
          commit = 0
        }
        unusualList.push(list[i])
      } else if (list[i].status == 1) {
        count++
      }
    }
    if (commit == 0) {
      wx.showToast({
        title: '请输入现场问题描述',
        image: "/images/warning.png"
      })
    } else if (count == list.length) {
      // console.log("全部通过")
      wx.showModal({
        title: "",
        content: "当前项目的排查结果为全部通过，将在点击确定后提交",
        success(res) {
          if (res.confirm) {
            // console.log('用户点击确定')
            that.commitForm("pass")
          }
        }
      })
    } else {
      this.commitForm(unusualList)
    }
  }, 1000),

  commitForm: function(type) {
    let that = this
    wx.showLoading({
      title: '正在提交',
      mask: true
    })
    for (let i = 0; i < this.data.checkItemList[0].contentList.length; i++) {
      this.data.checkItemList[0].contentList[i].schoolId = app.globalData.departmentId
      this.data.checkItemList[0].contentList[i].category = this.data.category
      this.data.checkItemList[0].contentList[i].itemId = this.data.checkItemList[0].contentList[i].id
      this.data.checkItemList[0].contentList[i].item = this.data.checkItemList[0].item
      this.data.checkItemList[0].contentList[i].address = this.data.checkItemList[0].address
      this.data.checkItemList[0].contentList[i].deviceName = this.data.deviceName
      this.data.checkItemList[0].contentList[i].deviceId = this.data.deviceId
      this.data.checkItemList[0].contentList[i].userId = app.globalData.userId
      this.data.checkItemList[0].contentList[i].realname = app.globalData.realname
      this.data.checkItemList[0].contentList[i]["schoolId"] = parseInt(app.globalData.departmentId)
    }
    wx.request({
      url: app.inspectUrl + '/WeChat/weChatSystem/addNFCInspectCondition',
      method: 'POST',
      data: this.data.checkItemList[0].contentList,
      dataType: 'json',
      fail(res) {
        wx.showToast({
          title: '网络异常！',
          mask: true,
          image: "/images/error.png"
        })
      },
      success: res => {
        if ("pass" != type) {
          console.log("有异常")
          wx.showLoading({
            title: '推送异常信息',
            mask: true
          })
          let countFail = 0,
          bind = [],
          unbind = []
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/getAccessTokenForSendMsg',
            method: 'GET',
            dataType: 'json',
            success: res => {
              console.log(res)
              let access_token = res.data.access_token
              wx.request({
                url: app.inspectUrl + '/WeChat/weChatSystem/getChargeManWeChatId',
                method: 'POST',
                data: {
                  categoryId:this.data.checkItemList[0].contentList[0].categoryId,
                  schoolId: app.globalData.departmentId
                },
                dataType: 'json',
                success: res => {
                  let chargeManNumber = res.data.length
                  // if (res.data) {
                  for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].res == "fail") {
                      unbind.push(res.data[i].msg)
                    } else {
                      bind.push(res.data[i].msg)
                    }
                  }
                  for (let i = 0; i < type.length; i++) {
                    let reqData = {
                      schoolId: parseInt(app.globalData.departmentId),
                      safetyLevel: 5,
                      address: this.data.checkItemList[0].address,
                      content: type[i].recordContent,
                      photo: type[i].imageUrl.join(","),
                      video :  type[i].video,
                      reporter: app.globalData.userId,
                      categoryId: type[i].categoryId,
                      // inspectConditionId: inspectConditionId[i],
                      itemContent: type[i].content,
                      latitude: this.data.latitude,
                      longitude: this.data.longitude,
                      altitude: this.data.altitude
                    }
                    console.log(reqData, "!!!!!!!!!!!!!!!!!")
                    wx.request({
                      url: app.inspectUrl + '/WeChat/weChatSystem/safetyReport',
                      method: 'POST',
                      data: reqData,
                      dataType: 'json',
                      success: res => {
                        if ('success' == res.data.res) {
                          if (chargeManNumber){
                            for (let i = 0; i < bind.length; i++) {
                              console.log(reqData, bind[i])
                              let datetime = util.formatTime(new Date())
                              wx.request({
                                url: app.inspectUrl + '/WeChat/weChatSystem/sendMessage',
                                data: {
                                  template: 1,
                                  accessToken: access_token,
                                  touser: bind[i],
                                  safetySceneId: res.data.data,
                                  miniprogram: {
                                    appid: 'wxfb5354f928ccc68e',
                                    pagepath: 'pages/indexBlank/indexBlank'
                                  },
                                  data: {
                                    first: {
                                      value: "【NFC巡检异常】"
                                    },
                                    keyword1: {
                                      value: app.globalData.realname
                                    },
                                    keyword2: {
                                      value: datetime
                                    },
                                    keyword3: {
                                      value: `NFC巡检时在${this.data.checkItemList[0].address}发现异常，请及时查看!`
                                    }
                                  }
                                },
                                method: 'POST',
                                dataType: 'json'
                              })
                            }

                          }
                        } else {
                          countFail++
                        }
                      },
                      fail: () => {
                        wx.showToast({
                          title: '网络异常！',
                          mask: true,
                          image: "/images/error.png"
                        })
                      }
                    })
                  }
                // }
                },
                fail: () => {
                  wx.showToast({
                    title: '网络异常！',
                    mask: true,
                    image: "/images/error.png"
                  })
                },
                complete: () => {
                  if (countFail != 0) {
                    wx.showToast({
                      title: `有${countFail}个异常上报失败！`,
                      mask: true,
                      icon: "none"
                    })
                  }
                  // console.log(unbind)
                  if (unbind.length != 0) {
                    let msg = unbind.join("、") + "主管未绑定服务号，无法正常接收推送！"
                    wx.showModal({
                      title: "提示",
                      showCancel: false,
                      content: msg,
                      success(res) {
                        if (res.confirm) {
                          let pages = getCurrentPages(); //当前页面
                          let prevPage = pages[pages.length - 2]; //上一页面
                          prevPage.setData({ //直接给上移页面赋值
                            submitRefresh: 1
                          });
                          // 提示框隐藏后 跳转
                          wx.navigateBack({
                            delta: 1
                          })
                        }
                      }
                    })
                  } else {
                    setTimeout(function() {
                      let pages = getCurrentPages(); //当前页面
                      let prevPage = pages[pages.length - 2]; //上一页面
                      prevPage.setData({ //直接给上移页面赋值
                        submitRefresh: 1
                      });
                      // 提示框隐藏后 跳转
                      wx.navigateBack({
                        delta: 1
                      })
                    }, 1000)
                  }

                }
              })
            },
            fail: () => {
              wx.showToast({
                title: '网络异常！',
                mask: true,
                image: "/images/error.png"
              })
            }
          })
        }else{
          wx.showToast({
            title: '提交成功！',
            mask: true
          })
          setTimeout(function() {
            let pages = getCurrentPages(); //当前页面
            let prevPage = pages[pages.length - 2]; //上一页面
            prevPage.setData({ //直接给上移页面赋值
              submitRefresh: 1
            });
            // 提示框隐藏后 跳转
            wx.navigateBack({
              delta: 1
            })
          }, 1000)
        }
      }
    })
  },

  //接触绑定
  unbind:function(e){
    let aid = this.data.aid
    let address = this.data.checkItemList[0].address
    wx.showModal({
      title: "",
      content: "是否将NFC卡片与该设备解除绑定",
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/unNFCbinding',
            method: 'POST',
            dataType: 'json',
            data: {
              schoolId : parseInt(app.globalData.departmentId) ,
              macAddress : aid,
              type:parseInt(4),
              address: address
            },
            success: res => {
              if(res.data == 'success'){
                wx.showToast({
                  title: "解绑成功"
                })
                setTimeout(function() {
                  let pages = getCurrentPages(); //当前页面
                  let prevPage = pages[pages.length - 2]; //上一页面
                  prevPage.setData({ //直接给上移页面赋值
                    submitRefresh: 1
                  });
                  // 提示框隐藏后 跳转
                  wx.navigateBack({
                    delta: 1
                  })
                }, 1000)
              }
            }
          })
        }
      }
    })
  }
})

